from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.ext.webapp.util import login_required
import cgi
import os
import models

TEMPLATE_DIR =os.path.dirname(__file__) + '/../templates/'
MAP_API_KEY = 'ABQIAAAAp6aJBHOLDCY6lcurHdEbJhSWYZCbWjfCs_Jmwl_yfPdnGEcaQRSdqU2PtW7BVPAYBbzqS3tY7g8FpQ'

class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    index_path = os.path.join(TEMPLATE_DIR,  "index.html")
    templatedata ={'api_key':MAP_API_KEY}
    if user:
        templatedata['username'] = user.nickname()
        map = models.Map.all()
        if map:
            map.filter("user =",  user)
            templatedata['maps'] = map
    else:
        nickname = None
    self.response.out.write(template.render(index_path, templatedata))
        
class SignInPage(webapp.RequestHandler):
    def get(self):
        self.redirect(users.create_login_url("/"))
        
class SignOutPage(webapp.RequestHandler):
    def get(self):
        self.redirect(users.create_logout_url("/"))

class SavePage(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user:
            mapname = cgi.escape(self.request.get('map_name'))
            urlname = mapname.replace(" ", "-")
            
            # Check if a map with this name already exists for this user
            map_query = models.Map.all()
            map_query.filter("user =",  user)
            map_query.filter("urlname =",  urlname)
            savemap = map_query.get()
            if not(savemap):
                savemap = models.Map(user= user, urlname = urlname)
            
            savemap.name = mapname
            savemap.center = self.request.get('map_center')
            savemap.zoom = int(self.request.get('map_zoom'))
           
            markerlist = []
            for tempmarker in self.request.get('map_markers').split(";"):
                if tempmarker:
                    markerlist += [db.GeoPt(tempmarker)]
            if markerlist != []:
                savemap.markers = markerlist
            
            savemap.put()
            self.redirect("/map/%s/%s/" %  (user, urlname))
        
class MapPage(webapp.RequestHandler):
    @login_required
    def get(self,  user,  mapname):
        current_user = users.get_current_user()
        index_path = os.path.join(TEMPLATE_DIR,  "index.html")
        templatedata ={'api_key':MAP_API_KEY}
        
        if user == current_user.nickname():
            templatedata['username'] = current_user.nickname()
            map_query = models.Map.all()            
            map_query.filter("user =",  current_user)
            all_maps = map_query.fetch(1000)
            if all_maps:
                templatedata['maps'] = all_maps
                
                map_query.filter("urlname =",  mapname)
                map = map_query.get()
                templatedata['currentmap'] = map
                self.response.out.write(template.render(index_path, templatedata))
        else:
            # TODO: Display error before redirect
            self.redirect("/")
    def post(self, user,  mapname):
        user_address = self.request.get("email_to")
        current_user = users.get_current_user()
        if current_user:
            map_url = self.request.get("map_url")
            sender = current_user.email()
            subject = 'Sharing My Running Route With You'
            body = """
Check out this map I made on route-running.appspot.com!
                
%s
""" % map_url
            html = """
<html><body>
<p>Check out this map I made on <a href="http://route-running.appspot.com">route-running.appspot.com</a>!</p>
<br />
<img src="%s"></img>
<br />
<a href="%s">Link to Map</a>
</body></html>
""" % (map_url,map_url)
            mail.send_mail(sender, user_address, subject, body,html=html)
            self.redirect(self.request.url)
            
class DeletePage(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user:
            mapname = cgi.escape(self.request.get('map_name'))
            urlname = mapname.replace(" ", "-")
            
            # Check if a map with this name already exists for this user
            map_query = models.Map.all()
            map_query.filter("user =",  user)
            map_query.filter("urlname =",  urlname)
            savemap = map_query.get()
            if savemap:
                savemap.delete()
        self.redirect("/settings/")

class AboutPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        about_path = os.path.join(TEMPLATE_DIR,  "about.html")
        templatedata ={'api_key':MAP_API_KEY}
        if user:
            templatedata['username'] = user.nickname()
        else:
            nickname = None
        self.response.out.write(template.render(about_path, templatedata))
        
class SettingsPage(webapp.RequestHandler):
    @login_required
    def get(self):
        current_user = users.get_current_user()
        html_path = os.path.join(TEMPLATE_DIR,  "settings.html")
        
        templatedata ={'api_key':MAP_API_KEY}
        templatedata['username'] = current_user.nickname()
        
        map_query = models.Map.all()
        map_query.filter("user =",  current_user)
        all_maps = map_query.fetch(1000)
        if all_maps:
            templatedata['maps'] = all_maps
            
        self.response.out.write(template.render(html_path, templatedata))
        
class HelpPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        help_path = os.path.join(TEMPLATE_DIR,  "help.html")
        templatedata ={'api_key':MAP_API_KEY}
        if user:
            templatedata['username'] = user.nickname()
        else:
            nickname = None
        self.response.out.write(template.render(help_path, templatedata))